package create;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;

import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.multimedia.jolitorask.client.ClientLocalHome;
import org.multimedia.jolitorask.client.exception.LoginException;




 public class NewClient extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    

		private static final long serialVersionUID = 1L;
		private static final String JNDI_NAME = "clientLocal";
		
		public static final String OK = "0";
		public static final String BAD_LOGIN = "-1";
		public static final String URL_EXISTS = "-2";
		public static final String SYNTAX_ERROR = "-3";
		public static final String OTHER = "-4";
		
		public NewClient() {
			super();
		}   	
		
		@SuppressWarnings("unchecked")
		protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

			
			    res.setContentType("text/plain");
			    PrintWriter out = res.getWriter();
			    
			    String login;
			    String pass;
			    String email;
			    String url;
			    
			    /* On recupere le login */
			    if( (login=req.getParameter("login")) == null){
			    	out.println(SYNTAX_ERROR);
			    	return;
			    }
			    
			    /* On recupere le password */
			    if( (pass=req.getParameter("password")) == null){
			    	out.println(SYNTAX_ERROR);
			    	return;
			    }
			    
			    /* On recupere l'email */
			    if( (email=req.getParameter("email")) == null){
			    	out.println(SYNTAX_ERROR);
			    	return;
			    }
			    
			    /* On recupere l'url */
			    if( (url=req.getParameter("url")) == null){
			    	out.println(SYNTAX_ERROR);
			    	return;
			    }
			    
			    
			    /* Creation */
			    Context initContext = null;
			    Hashtable env = new Hashtable(1);
			    Object beanObject = null;
			    try {
			    	
			    	
			    	initContext = new javax.naming.InitialContext(env);
			    	beanObject = initContext.lookup(JNDI_NAME);
			    	ClientLocalHome home = (ClientLocalHome) beanObject;
					home.create(null, login, pass, email, url);
		
			    	
			    }
			    catch(CreateException e) {
			    	
			    	if(e instanceof LoginException )
			    		out.println(e.getMessage());
			    	else out.println(OTHER);
			    	
			    	return;
			    }
			    catch(NamingException e2){
			    	out.println(OTHER);
			    	return;
			    }
			    
			    out.println(OK);
		}  	
		
		protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		}   	  	    
 }